using UnityEngine;
using System.Collections;
namespace EnemyStates
{
    public class Searching : FSMBehaviour
    {
        Enemy m_Owner;
        //Cantidad de veces que busca en una posicion random alrededor de donde fue a buscar
        const int c_TotalSearchAmount = 3;


        const float c_IdleTime = 5.0f;
        const float c_SearchTime = 60.0f;
        float idleTimer = 0;
        float searchTimer = 0;

        const int c_RNGTries = 3;


        bool m_LookNewPath = false;
        Vector3 m_LastSearchedPosition;
        public Searching(Enemy owner)
        {
            m_Owner = owner;
            m_LastSearchedPosition = owner.transform.position;
        }
        public override void Update()
        {
            base.Update();

            m_Owner.RotateEye();
            m_Owner.UpdateEyeDirection();

            //si ve a una personaje del jugador
            if (m_Owner.IsCharacterInSight())
            {
                m_Owner.SendEvent(ENEMYEVENTS.SEEPLAYER);
                return;
            }


            //si llego a algun punto de busqueda.
            if (m_Owner.m_Moving == false)
            {
                if (idleTimer >= c_IdleTime)
                {
                    idleTimer = 0;
                    //Si ya termino el tiempo que dura el estado.
                    if (searchTimer >= c_SearchTime)
                    {
                        m_Owner.SendEvent(ENEMYEVENTS.RETURN);
                        return;
                    }

                    /*int count = 0;

                    //Los lugares a buscar dependen de un random
                    //lo cual puede dar en lugares donde el personaje no se puede mover
                    //Si la cantidad de veces que el random da mal pasa cierto numero ignora ese movimiento. 
                    while (count < c_RNGTries)
                    {
                        if (m_Owner.MoveTo(GetSearchPoint()))
                        {
                            m_Owner.ResetEyeRotationParameters();
                            break; //para que salga de while
                        }
                        else
                        {
                            count++;
                        }
                    }
                    m_CurrentAmount++;*/

                    //Si hay puntos de busqueda.
                    if (m_Owner.m_SearchPositions.Count > 0)
                    {
                        m_LastSearchedPosition = m_Owner.m_SearchPositions.Pop();
                        m_Owner.MoveTo(m_LastSearchedPosition);
                    }
                    else
                    {
                       m_Owner.MoveTo(GetRandomSearchPoint(m_LastSearchedPosition));
                    }
                    if (m_Owner.m_Moving == true)
                    {
                        m_Owner.ResetEyeRotationParameters();
                    }
                }
                else
                {
                    idleTimer += Time.deltaTime;
                    m_Owner.m_CurrentTotalEyeRotation = 720;
                    m_Owner.m_EyeRotationMultiplier = 3;
                }
            }
            searchTimer += Time.deltaTime;
        }
        public override void OnEnable()
        {
            if (m_Owner.MoveTo(m_Owner.m_SearchPositions.Pop()) == false)
            {
                Debug.LogError("Enemigo no puede llegar al SearchPosition");
            }
            SoundManager.Instance.PlaySound("EnemyAlert",m_Owner.transform.position, true);
        }
        public override void OnDisable()
        {
            idleTimer = 0;
            searchTimer = 0;


            m_Owner.m_SearchPositions.Clear();
            m_Owner.StopMoving();
            m_Owner.ResetEyeRotationParameters();
        }
        /// <summary>
        /// Se va a llamar cuando hay escucha algo nuevo para que cambie de camino y se resetee el tiempo de busqueda.
        /// </summary>
        public void Reset()
        {
            idleTimer = c_IdleTime;
            searchTimer = 0;
            
            m_Owner.StopMoving();
        }
        /// <summary>
        /// Devuelve un vector random alrededor de cierto vector.
        /// </summary>
        /// <param name="aroundCenter">Vector desde el cual se calcula la posicion random.</param>
        /// <returns></returns>
        Vector3 GetRandomSearchPoint(Vector3 aroundCenter)
        {
            Vector3 direction;

            /*
            if (m_CurrentAmount == 0)
            {
                if (m_Owner.m_SearchDirection != Vector3.zero)
                {
                    direction = m_Owner.m_SearchDirection;
                }
                else
                {
                    return m_Owner.m_SearchPosition;
                }
            }
            else
            {
                direction = Random.insideUnitSphere;
                direction.y = 0;
            }*/

            direction = Random.insideUnitSphere;
            direction.y = 0;
            float distance = Random.Range(Enemy.c_MinSearchDistance, Enemy.c_MaxSearchDistance) *m_Owner.transform.localScale.x;

            return aroundCenter + direction * distance;

        }

    }
}
